package main

import (
	"fmt"
	"os"
	"os/signal"
	"shop_api/goods_web/utils"
	"syscall"

	"shop_api/goods_web/global"
	"shop_api/goods_web/initialize"
	"shop_api/goods_web/utils/register/consul"

	"github.com/satori/go.uuid"
	"go.uber.org/zap"
)

func main() {

	initialize.InitLogger()
	initialize.InitConfig()
	r := initialize.Routers()
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}
	initialize.InitSrvConn()

	//port, err := utils.GetFreePort()
	//if err == nil {
	//	global.ServerConfig.Port = port
	//}

	registerClient := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceID := uuid.NewV4().String()

	localHost, err := utils.GetLocalIP()
	if err != nil || localHost == "" {
		panic("get local ip failed")
	}
	err = registerClient.Register(localHost, global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, serviceID)
	if err != nil {
		zap.S().Panic("服务注册失败", err.Error())
	}

	zap.S().Infof("启动服务器，IP：%s，端口： %d", localHost, global.ServerConfig.Port)
	if err := r.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
		zap.S().Panic("启动失败", err.Error())
	}

	// 接收终止信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	if err = registerClient.DeRegister(serviceID); err != nil {
		zap.S().Error("注销失败", err.Error())
	} else {
		zap.S().Info("注销成功")
	}
}
